﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Web;
using DHQGHN.DAL.BO.DanhMuc;
using DHQGHN.DAL.BO.TDT;
using DHQGHN.DAL.Models.DanhMuc;
using DHQGHN.DAL.Models.TDT;

namespace DHQGHN.Services.TDT
{
    public class ResidentService : IResidentService
    {
        private ResidentBO residentBO;
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(ResidentService));
        #region Constructors
        /// <summary>
        /// 
        /// </summary>
        public ResidentService()
        {
            //string connString = ConfigurationManager.ConnectionStrings["DHQGHN_TDT.ConnectionString"].ConnectionString;
            residentBO = new ResidentBO(DHQGHN.DAL.Common.ConnectionUtil.TKTHDS_TDT_CONNECTION_STRING);
        }
        #endregion

        #region Service Methods
        /// <summary>
        /// 
        /// </summary>
        /// <param name="residentID"></param>
        /// <returns></returns>
        public RESIDENT GetByID(string residentID)
        {

            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new RESIDENT();
                }
                else
                {
                    string id = "-1";

                    if (string.IsNullOrEmpty(residentID))
                    {
                        Fault.ValidationFault fault = new Fault.ValidationFault()
                        {
                            Result = false,
                            Message = "Thiếu tham số",
                            Description = "Thiếu tham số"
                        };

                        throw new FaultException<Fault.ValidationFault>(fault);
                    }
                    id = residentID;
                    return residentBO.GetById(id);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="areaCode"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIdx"></param>
        /// <returns></returns>
        public IEnumerable<RESIDENT> GetByAreaCode(string areaCode, 
            string pageSize, string pageIdx)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new List<RESIDENT>();
                }
                else
                {
                    if (string.IsNullOrEmpty(areaCode)
                        || string.IsNullOrEmpty(pageSize)
                        || string.IsNullOrEmpty(pageIdx))
                    {
                        Fault.ValidationFault fault = new Fault.ValidationFault()
                        {
                            Result = false,
                            Message = "Thiếu tham số",
                            Description = "Thiếu tham số"
                        };

                        throw new FaultException<Fault.ValidationFault>(fault);
                    }

                    int ipageSize, ipageIdx;
                    if (int.TryParse(pageSize, out ipageSize) == false
                        || int.TryParse(pageIdx, out ipageIdx) == false)
                    {
                        Fault.ValidationFault fault = new Fault.ValidationFault()
                        {
                            Result = false,
                            Message = "Tham số PageSize (hoặc PageIdx) sai định dạng!",
                            Description = "Tham số PageSize (hoặc PageIdx) sai định dạng!"
                        };

                        throw new FaultException<Fault.ValidationFault>(fault);
                    }

                    return residentBO.GetByAREACode(areaCode, ipageSize, ipageIdx);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="commnuneCode"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIdx"></param>
        /// <returns></returns>
        public IEnumerable<RESIDENT> GetByCommuneCode(string commnuneCode, 
            string pageSize, string pageIdx)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new List<RESIDENT>();
                }
                else
                {
                    if (string.IsNullOrEmpty(commnuneCode)
                        || string.IsNullOrEmpty(pageSize)
                        || string.IsNullOrEmpty(pageIdx))
                    {
                        Fault.ValidationFault fault = new Fault.ValidationFault()
                        {
                            Result = false,
                            Message = "Thiếu tham số",
                            Description = "Thiếu tham số"
                        };

                        throw new FaultException<Fault.ValidationFault>(fault);
                    }

                    int ipageSize, ipageIdx;
                    if (int.TryParse(pageSize, out ipageSize) == false
                        || int.TryParse(pageIdx, out ipageIdx) == false)
                    {
                        Fault.ValidationFault fault = new Fault.ValidationFault()
                        {
                            Result = false,
                            Message = "Tham số PageSize (hoặc PageIdx) sai định dạng!",
                            Description = "Tham số PageSize (hoặc PageIdx) sai định dạng!"
                        };

                        throw new FaultException<Fault.ValidationFault>(fault);
                    }

                    return residentBO.GetByAREACode(commnuneCode, ipageSize, ipageIdx);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="resident"></param>
        public void AddResident(RESIDENT resident)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                }
                else
                {
                    residentBO.Save(resident);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="residentID"></param>
        public void DeleteResident(string residentID)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                }
                else
                {
                    residentBO.Delete(residentID);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="resident"></param>
        public void EditResident(RESIDENT resident)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                }
                else
                {
                    residentBO.Save(resident);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }


        public IEnumerable<RESIDENT> GetByHouseHoldID(string houseHoldId)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new List<RESIDENT>();
                }
                else
                {
                    return residentBO.GetByHouseHoldID(houseHoldId);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }

        public IEnumerable<PM3_RESIDENT> GetByHouseHoldIDForPM3(string houseHoldId, string residentID)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new List<PM3_RESIDENT>();
                }
                else
                {
                    return residentBO.GetByHouseHoldIDForPM3(houseHoldId, residentID);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }
        #endregion
    }
}